import { defineStore } from "pinia";
import { RouteRecordRaw } from 'vue-router';
import { accessRoutes, publicRoutes, constantRoutes } from '@/router/routes'
import { filterAsyncRoutes } from '@/utils/permission'
import fetchApi from '@/api/login'

interface PermissioState {
    isGetUserInfo: boolean; // 是否获取过用户信息
    isAdmin: 0 | 1; // 是否为管理员
    auths: string[]; // 当前用户权限
    modules: string[]; // 模块权限
    role: 0 | 1;
  }

const usePermissionStore = defineStore(
    'permission',
    {
        state: (): PermissioState => {
            return {
                isGetUserInfo: false,
                isAdmin: 0,
                auths: [],
                modules: [],
                role: 0
            }
        },
        actions: {
            setAuth(auths: string[], modules: string[]) {
                this.auths = auths;
                this.isGetUserInfo = true;
                this.modules = modules;
              },
            setIsAdmin(isAdmin: 0 | 1) {
                this.isAdmin = isAdmin;
            },
            resetState() {
                this.isGetUserInfo = false;
                this.isAdmin = 0;
                this.auths = [];
                this.modules = [];
                this.role = 0;
            },
                    /**
             * @name fetchAuths
             * @description 获取当前用户权限
             */
            async fetchAuths() {
                const res = await fetchApi.permission();
                console.log(res, 'res');
                
                if (res) {
                    this.setAuth(res.auths, res.modules);
                    this.setIsAdmin(res.is_admin || 0);
                }
                return res;
            },
        
            /**
             * @name buildRoutesAction
             * @description: 获取路由
             */
            async buildRoutesAction(): Promise<RouteRecordRaw[]> {
                // 404 路由一定要放在 权限路由后面
                let routes: RouteRecordRaw[] = [...constantRoutes, ...accessRoutes, ...publicRoutes];
                console.log(this.isAdmin, this.modules, routes, 'this.isAdmin');
        
                if (this.isAdmin !== 1) {
                // 普通用户
                // 1. 方案一：过滤每个路由模块涉及的接口权限，判断是否展示该路由
                // 2. 方案二：直接检索接口权限列表是否包含该路由模块，不做细分，axios同一拦截
                console.log(this.isAdmin, this.modules, accessRoutes, 'this.isAdmin0');
                
                routes = [
                    ...constantRoutes,
                    ...filterAsyncRoutes(accessRoutes, this.modules),
                    ...publicRoutes,
                ];
                }
        
                return routes;
            },
        
        }
    }
)

export default usePermissionStore